import proxy from "./proxy";
import service from "./service";
import storage from "./storage";
import utils from "./utils";

const checkRefreshPage = async () => {
  if (await storage.get('auto-refresh') === true && await proxy.get()) {
    utils.refreshCurrentPage();
  }
}

const defaultConfig = {
  contexts: ['all'],
  type: 'checkbox',
  documentUrlPatterns: ['http://*/*', 'https://*/*', 'file://*/*']
}
export default {
  async setMenu() {
    try {
      const {
        rules: {
          list: rules,
          defaultRulesIsDisabled,
          allowMultipleChoice
        }
      } = await service.getInitInfo();
      chrome.contextMenus.removeAll();
      chrome.contextMenus.create({
        id: 'action:defaultRule',
        title: chrome.i18n.getMessage('defaultRule'),
        checked: !defaultRulesIsDisabled,
        ...defaultConfig
      })
      chrome.contextMenus.create({
        id: 'separator-1',
        type: 'separator'
      });
      rules.forEach(rule => {
        if (rule.name.match(/^\r/)) return
        chrome.contextMenus.create({
          id: rule.name,
          title: rule.name,
          checked: rule.selected,
          ...defaultConfig
        });
      });
      chrome.contextMenus.create({
        id: 'separator-2',
        type: 'separator'
      });
      chrome.contextMenus.create({
        id: 'action:proxy',
        checked: await proxy.get(),
        title: chrome.i18n.getMessage('enable'),
        ...defaultConfig
      })
      chrome.contextMenus.create({
        id: 'action:multiple',
        checked: !!allowMultipleChoice,
        title: chrome.i18n.getMessage('tip_multiple'),
        ...defaultConfig
      })
      chrome.contextMenus.create({
        id: 'action:auto-refresh',
        checked: await storage.get('auto-refresh') === true,
        title: chrome.i18n.getMessage('tip_refresh'),
        ...defaultConfig
      })

      chrome.contextMenus.onClicked.addListener(async ({menuItemId, checked}) => {
        switch (menuItemId) {
          case 'action:defaultRule':
            await service.changeDefaultRule(!!checked);
            await checkRefreshPage();
            await service.getInitInfo()
            break
          case 'action:proxy':
            await (checked ? proxy.enable() : proxy.disable())
            await proxy.get();
            break
          case 'action:multiple':
            await service.setAllowMultipleChoice(!!checked);
            break
          case 'action:auto-refresh':
            await storage.set('auto-refresh', !!checked);
            break
          default:
            const rule = rules.find(item => item.name === menuItemId)
            await service.setRuleEnable(rule, !!checked);
            await checkRefreshPage();
            await service.getInitInfo()
        }
      })
    } catch (e) {
    }
  }
}
